package org.flown.shop.controller;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.flown.shop.SessionAttribute;
import org.flown.shop.dto.UserDTO;
import org.flown.shop.entity.User;
import org.flown.shop.service.ServiceResult;
import org.flown.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.PrintWriter;


@Controller
@RequestMapping("/user")
public class UserController
{
    @Autowired
    private UserService service_user;


    @ResponseBody
    @RequestMapping(value = {"/getUserByID", "/{id}"})
    public UserDTO getUserByID(@PathVariable @RequestParam int id) {return this.service_user.getUserDTOByID(id);}

    @ResponseBody
    @RequestMapping(value = {"/getUserByUsername", "/username/{username}"})
    public UserDTO getUserByUsername(@PathVariable @RequestParam String username) {return this.service_user.getUserDTOByUserName(username);}


    @PostMapping(value = "/register", params = {"username", "password"})
    public void register(HttpServletResponse response, @Valid User user)
            throws IOException
    {
        PrintWriter out = response.getWriter();
        if (user == null)
        {
            out.println("注册失败");
            out.close();
            return;
        }
        ServiceResult result = this.service_user.register(user.getNickname(), user.getUsername(), user.getPassword());
        switch (result) {
            case SUCCESS -> out.println("注册成功");
            case FAILED -> out.println("注册失败");
            case EXISTS -> out.println("用户已存在");
            default -> {}
        }
        out.flush();
        out.close();
    }
    


    @PostMapping(value = "/login", params = {"username", "password"})
    public void login(HttpServletResponse response,
        HttpSession session,
        @Valid User user)
            throws IOException
    {
        PrintWriter out = response.getWriter();
        ServiceResult result = this.service_user.login(user.getUsername(), user.getPassword());
        switch (result) {
            case SUCCESS -> {
                session.setAttribute(SessionAttribute.USER.getName(), this.getUserByUsername(user.getUsername()));
                out.println("登录成功");
            }
            case FAILED -> out.println("密码错误");
            case NOT_EXISTS -> out.println("用户不存在");
            default -> {}
        }
        out.flush();
        out.close();
    }


}

